<template>
  <div>
    <el-form label-width="100px" :model="form" ref="ruleForm">
      <!-- 题目创建 -->
      <el-form-item label="题目" prop="title" required>
        <el-input
          type="text"
          v-model="form.title"
          placeholder="请输入题目"
          v-on:click.native="createTitle()"
        ></el-input>
        <el-dialog title="题目" :visible.sync="titleVisible">
          <el-input
            ref="dialogInput"
            placeholder="请输入题目"
            v-model="anotherForm.title"
            type="textarea"
            rows="6"
          >
          </el-input>
          <div slot="footer">
            <el-button type="primary" @click.native="titleVisible = false"
              >取消</el-button
            >
            <el-button type="primary" @click.native="sureCreateTitle()"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-form-item>
      <!-- 描述 -->
      <el-form-item label="题目描述" prop="description" required>
          <div class="local-quill-editor">
            <quill-editor
              ref="myLQuillEditor"
              v-model="form.description"
              :options="editorOption"
              class="editor"
              @change="onEditorChange"
            ></quill-editor>
          </div>
      </el-form-item>
      <!-- 输入描述 -->
      <el-form-item label="输入描述" prop="inputDescription" required>
        <el-input
          type="textarea"
          rows="1"
          v-model="form.inputDescription"
          placeholder="请填写输入描述"
          v-on:click.native="createInputDescription()"
        ></el-input>
        <el-dialog title="输入描述" :visible.sync="inputDescriptionVisible">
          <el-input
            ref="dialogInput"
            v-model="anotherForm.inputDescription"
            placeholder="请填写输入描述"
            type="textarea"
            rows="6"
          >
          </el-input>
          <div slot="footer">
            <el-button
              type="primary"
              @click.native="inputDescriptionVisible = false"
              >取消</el-button
            >
            <el-button
              type="primary"
              @click.native="sureCreateInputDescription()"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-form-item>
      <!-- 输出描述 -->
      <el-form-item label="输出描述" prop="outputDescription" required>
        <el-input
          type="textarea"
          rows="1"
          v-model="form.outputDescription"
          placeholder="请填写输出描述"
          v-on:click.native="createOutputDescription()"
        ></el-input>
        <el-dialog title="输出描述" :visible.sync="outputDescriptionVisible">
          <el-input
            ref="dialogInput"
            v-model="anotherForm.outputDescription"
            placeholder="请填写输出描述"
            type="textarea"
            rows="6"
          >
          </el-input>
          <div slot="footer">
            <el-button
              type="primary"
              @click.native="outputDescriptionVisible = false"
              >取消</el-button
            >
            <el-button
              type="primary"
              @click.native="sureCreateOutputDescription()"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-form-item>
      <el-form-item>
        <el-row>
          <el-col :span="8">
            <span>时间限制(ms)</span>
            <el-input-number
              v-model="form.timeLimit"
              :min="1000"
              :max="1000000"
            ></el-input-number>
          </el-col>
          <el-col :span="8">
            <span>内存限制mb</span>&nbsp;
            <el-input-number v-model="form.memoryLimit" :min="20" :max="2048"></el-input-number>
          </el-col>
          <el-col :span="8">
            <span>难度</span>
            <el-select v-model="form.level" placeholder="请选择">
              <el-option
                v-for="item in anotherForm.level"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>
      <!-- 提示 -->
      <el-form-item label="提示" required>
        <el-input
          type="textarea"
          placeholder="请填写题目提示"
          v-model="form.hint"
          rows="1"
          v-on:click.native="createhint()"
        ></el-input>
        <el-dialog title="提示" :visible.sync="hintVisible">
          <el-input
            ref="dialogInput"
            placeholder="请填写题目提示"
            v-model="anotherForm.hint"
            type="textarea"
            rows="6"
          >
          </el-input>
          <div slot="footer">
            <el-button type="primary" @click.native="hintVisible = false"
              >取消</el-button
            >
            <el-button type="primary" @click.native="sureCreatehint()"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-form-item>
      <!-- 知识点 -->
      <el-form-item prop="tags" required label="知识点">
        <el-tag
          :key="index"
          v-for="(item, index) in form.tags"
          closable
          :disable-transitions="false"
          @close="form.tags.splice(index, 1)"
        >
          {{ item.name }}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="inputVisible"
          v-model="inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm"
          @blur="handleInputConfirm"
        >
        </el-input>
        <el-button
          style="margin: 0"
          v-else
          class="button-new-tag"
          size="small"
          @click="showInput"
          >+ New Tag</el-button
        >
      </el-form-item>
      <!-- 样例 -->
      <el-form-item label="输入样例">
        <el-row>
          <el-col :span="12">
            <el-input
              type="textarea"
              placeholder="请填写输入样例"
              rows="3"
              class="inputCSS"
              v-if="form.ioSamples"
              v-model="form.ioSamples[0].inputSample"
              v-on:click.native="createInputSample"
            ></el-input>
          </el-col>
          <el-dialog :visible.sync="inputSampleVisible" title="输入样例">
            <el-input
              ref="dialogInput"
              placeholder="请填写输入样例"
              v-model="anotherForm.ioSamples[0].inputSample"
              type="textarea"
              rows="6"
            ></el-input>
            <div slot="footer">
              <el-button
                type="primary"
                @click.native="inputSampleVisible = false"
                >取消</el-button
              >
              <el-button type="primary" @click.native="sureCreateInputSanple"
                >确定</el-button
              >
            </div>
          </el-dialog>
          <el-col :span="2">输出样例</el-col>
          <el-col :span="10">
            <el-input
              type="textarea"
              placeholder="请填写输出样例"
              class="ouputCSS"
              rows="3"
              v-if="form.ioSamples"
              v-model="form.ioSamples[0].outputSample"
              v-on:click.native="createOutputSample"
            ></el-input>
            <el-dialog title="输出样例" :visible.sync="outputSampleVisible">
              <el-input
                ref="dialogInput"
                v-if="anotherForm.ioSamples"
                placeholder="请填写输出样例"
                v-model="anotherForm.ioSamples[0].outputSample"
                type="textarea"
                rows="6"
              ></el-input>
              <div slot="footer">
                <el-button
                  type="primary"
                  @click.native="outputSampleVisible = false"
                  >取消</el-button
                >
                <el-button type="primary" @click.native="sureCreateOutputSanple"
                  >确定</el-button
                >
              </div>
            </el-dialog>
          </el-col>
        </el-row>
      </el-form-item>
      <!--提交测试用例-->
      <el-form-item label="测试用例：" prop="file">
        <el-row>
          <el-col :span="8">
            <el-upload
              class="upload-demo"
              accept="zip"
              drag
              multiple
              action=""
              :limit="1"
              :before-upload="beforeZipUpload"
              :http-request="
                (param) => {
                  handleRequest(param);
                }
              "
              :show-file-list="true"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>

              <div slot="tip" v-if="this.form.testCaseId" style="color: red">
                <span class="testfile">测试文件id：{{ this.form.testCaseId }}</span>
                 <el-button size="mini" class="btn_primary download">下载<i class="el-icon-download el-icon--right"></i></el-button>
              </div>
            </el-upload></el-col
          >
          <el-col :span="8">
            <span>
              <div class="el-upload__tip" slot="tip">
                备注：只能上传zip文件，且不超过500kb
                <span style="font-weight: bold; text-decoration: underline"
                  >(1.in和1.out是一组对应的测试用例，2.in和2.out.......以此类推，.in是输入用例，.out是输出用例，将它们放进一个压缩包上传)</span
                >
              </div>
            </span></el-col
          >
        </el-row>
      </el-form-item>
      <!--参考答案
      <el-form-item label="参考答案">
        <el-input
          v-model="form.answer"
          v-on:click.native="createAnswer"
          type="textarea"
          placeholder="请填写参考答案"
          class="answerCSS"
          rows="2"
        ></el-input>
        <el-dialog title="参考答案" :visible.sync="answerVisible">
          <el-input
            ref="dialogInput"
            placeholder="请填写参考答案"
            v-model="anotherForm.answer"
            type="textarea"
            rows="6"
          ></el-input>
          <div slot="footer">
            <el-button
              type="primary"
              @click.native="answerVisible = false"
              >取消</el-button
            >
            <el-button type="primary" @click.native="sureCreateAnswer"
              >确定</el-button
            >
          </div>
        </el-dialog>
      </el-form-item>-->
      <!-- 提交 -->
      <el-form-item>
        <el-button @click="resetForm" type="info" round class="cancel1"
          >重置</el-button
        >
        <el-button type="primary" round  v-debounce="upload">提交</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="UploadVisible">
      <h3>题目预览</h3>
      <div class="content" v-if="form">
        <program-detail :question="form"></program-detail>
      </div>
      <div slot="footer">
        <el-button type="info" @click.native="UploadVisible = false"
          >取消</el-button
        >
        <el-button
          type="primary"
          round
          :loading="submitLoading"
          v-debounce="retUpload"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
//引入富文本插件vue-quill-editor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import  { quillEditor,Quill } from 'vue-quill-editor'
import ImageResize from 'quill-image-resize-module'
Quill.register('modules/imageResize', ImageResize)

// 工具栏配置项
const toolbarOptions = [
  // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['bold', 'italic', 'underline', 'strike'],
  // 引用  代码块-----['blockquote', 'code-block']
  ['blockquote', 'code-block'],
  // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
  [{ header: 1 }, { header: 2 }],
  // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ list: 'ordered' }, { list: 'bullet' }],
  // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
  [{ script: 'sub' }, { script: 'super' }],
  // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
  [{ indent: '-1' }, { indent: '+1' }],
  // 文本方向-----[{'direction': 'rtl'}]
  [{ direction: 'rtl' }],
  // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
  [{ size: ['small', false, 'large', 'huge'] }],
  // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
  [{ color: [] }, { background: [] }],
  // 字体种类-----[{ font: [] }]
  [{ font: [] }],
  // 对齐方式-----[{ align: [] }]
  [{ align: [] }],
  // 清除文本格式-----['clean']
  ['clean'],
  // 链接、图片、视频-----['link', 'image', 'video']
  ['image',]
]

import { testCase, uploadPGProblem, editPGProblem } from "@/api/question.js";
import programDetail from "@/components/programDetail.vue";
export default {
  components: { quillEditor,programDetail },
  name: "programCreate",
  data() {
    return {
      answerVisible: false,
      isAdd: true,
      UploadVisible: false,
      titleVisible: false,
      descriptionVisible: false,
      inputDescriptionVisible: false,
      outputDescriptionVisible: false,
      hintVisible: false,
      inputVisible: false,
      inputValue: "",
      inputSampleVisible: false,
      outputSampleVisible: false,
      fileChange: false,
      submitLoading: false,
      tagValue: {},
      form: {
        visible: true,
        title: null,
        description: null,
        inputDescription: null,
        outputDescription: null,
        timeLimit: 1000,
        memoryLimit: 100,
        level: 0,
        hint: null,
        tags: [],
        ioSamples: [
          {
            inputSample: "",
            outputSample: "",
          },
        ],
        testCaseId: null,
        userId: null,
        answer:""
      },
      anotherForm: {
        title: "",
        description: "",
        inputDescription: "",
        outputDescription: "",
        level: [
          { value: 0, label: "easy" },
          { value: 1, label: "medium" },
          { value: 2, label: "hard" },
          { value: 3, label: "insuperable" },
          { value: 4, label: "hell" },
        ],
        hint: "",
        ioSamples: [
          {
            inputSample: "",
            outputSample: "",
          },
        ],
        tags: [],
        answer:""
      },
      editorOption: {
        modules: {
          toolbar: toolbarOptions,
          imageResize: {
                displayStyles: {
                  backgroundColor: 'black',
                  border: 'none',
                  color: 'white'
                },
                modules: ['Resize', 'DisplaySize', 'Toolbar']
              },
        },
        theme: 'snow',
        placeholder: '请输入正文'
        // Some Quill optiosn...
      }
    };
  },
  created() {
    if (this.$route.params.data) {
      this.isAdd = false;
      this.form = this.$route.params.data;
      let levels = ["easy", "medium", "hard", "insuperable", "hell"];
      for (let i = 0; i < 5; i++) {if (levels[i] == this.form.level) this.form.level = i;}
      this.$route.meta.title = "编程题编辑";
      console.log(this.form.ioSamples.length);
      if (this.form.ioSamples.length == 0) {
        this.form.ioSamples = [
          {
            inputSample: "",
            outputSample: "",
          },
        ];
      }
    }
    // 获取当前用户信息
    this.form.userId = JSON.parse(localStorage.getItem("user")).userId;
  },
  methods: {
    onEditorChange(e){
      //富文本编辑器失焦事件
       if(this.form.description.length/1024/1024>=3){
         this.$message.info("上传的图片超过3m，请压缩照片重新上传！")
       }
    },
    //使得dialog输入框获得焦点
    inputFocus() {
      this.$nextTick(() => {
        this.$refs.dialogInput.focus();
      });
    },
    // 题目
    createTitle() {
      this.anotherForm.title = this.form.title;
      this.titleVisible = true;
      this.inputFocus();
    },
    sureCreateTitle() {
      this.form.title = this.anotherForm.title;
      this.titleVisible = false;
    },
    // 输入描述
    createInputDescription() {
      this.anotherForm.inputDescription = this.form.inputDescription;
      this.inputDescriptionVisible = true;
      this.inputFocus();
    },
    sureCreateInputDescription() {
      this.form.inputDescription = this.anotherForm.inputDescription;
      this.inputDescriptionVisible = false;
    },
    // 输出描述
    createOutputDescription() {
      this.anotherForm.outputDescription = this.form.outputDescription;
      this.outputDescriptionVisible = true;
      this.inputFocus();
    },
    sureCreateOutputDescription() {
      this.form.outputDescription = this.anotherForm.outputDescription;
      this.outputDescriptionVisible = false;
    },
    // 提示
    createhint() {
      this.anotherForm.hint = this.form.hint;
      this.hintVisible = true;
      this.inputFocus();
    },
    sureCreatehint() {
      this.form.hint = this.anotherForm.hint;
      this.hintVisible = false;
    },
    // 知识点
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.form.tags.push({ name: inputValue });
      }
      this.inputVisible = false;
      this.inputValue = "";
    },
    // 输入样例
    createInputSample() {
      this.anotherForm.ioSamples[0].inputSample =
        this.form.ioSamples[0].inputSample;
      this.inputSampleVisible = true;
      this.inputFocus();
    },
    sureCreateInputSanple() {
      this.form.ioSamples[0].inputSample =
        this.anotherForm.ioSamples[0].inputSample;
      this.inputSampleVisible = false;
    },
    // 输出样例
    createOutputSample() {
      this.anotherForm.ioSamples[0].outputSample =
        this.form.ioSamples[0].outputSample;
      this.outputSampleVisible = true;
      this.inputFocus();
    },
    sureCreateOutputSanple() {
      this.form.ioSamples[0].outputSample =
        this.anotherForm.ioSamples[0].outputSample;
      this.outputSampleVisible = false;
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeZipUpload(file) {
      //文件是否为zip
      if (file.type.indexOf("zip") < 0) {
        this.$message.warning("只能上传zip文件");
        return false;
      }
      //zip不能大于2M
      if (file.size > 1024 * 500 * 1) {
        this.$message.warning("zip文件不能大于500kb");
        return false;
      }
      return true;
    },

    handleRequest(param) {
      this.file = param.file;
      this.fileChange = true; //修改了测试文件，重新上传测试文件
      //手动触发验证
      this.$refs.ruleForm.validateField("file");
    },
    async retUpload() {
      this.submitLoading = true; 
      if (this.fileChange) {
        //封装文件传输
        var param = new FormData();
        param.append("testCaseFile", this.file);
        await testCase(param)
          .then((res) => {
            this.form.testCaseId = res.data.testCaseId;
          })
          .catch(() => {
            this.$message.error("提交测试文件失败");
            this.submitLoading = false;
            return;
          });
      }
      if (this.form.ioSamples[0].inputSample == "") {
        delete this.form.ioSamples;
      } 
      if (this.isAdd) {
        //添加题目
        uploadPGProblem(this.form)
          .then((res) => {
            //console.log(res);
            this.$message.success("题目上传成功！");
            this.$router.push({
              name: "questionModule/questionList",
              params: { mark: true },
            });
          })
          .catch(() => {
            this.$message.error("题目上传失败");
          })
          .finally(() => {
            this.submitLoading = false;
          });
      } else {
        delete this.form.removeLoading;
        delete this.form.type;
        editPGProblem(this.form)
          .then((res) => {
            this.$message.success("题目编辑成功！");
            this.$router.push({
              name: "questionModule/questionList",
              params: { mark: true },
            });
          })
          .catch(() => {
            this.$message.error("题目编辑失败");
          })
          .finally(() => {
            this.submitLoading = false;
          });
      }
    },
    // 提交
    upload() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!this.file && !this.form.testCaseId) {
            this.$message.warning("请上传测试用例zip文件");
            return;
          }
          console.log(this.form )
          this.UploadVisible = true;
        }
      });
    },
    //重置
    resetForm() {
      Object.assign(this.$data, this.$options.data());
    },
    /**
    //确定参考答案
     sureCreateAnswer() {
      this.form.answer =this.anotherForm.answer
      this.answerVisible = false;
    },
    //创建参考答案
    createAnswer(){
     this.anotherForm.answer =this.form.answer;
      this.answerVisible = true;
      this.inputFocus();
    } */
  },
};
</script>

<style>
.el-form-item {
  margin-bottom: 16px;
  text-align: left;
}
.inputCSS {
  width: 450px;
}
.ouputCSS,.answerCSS{
  width: 450px;
}
.cancel1 {
  margin-left: 450px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.sample {
  border: dimgray solid 1px;
  width: 100%;
  height: 200px;
}
.upload-demo {
  margin-top: 10px;
}
</style>
